package Stage_2;
import Stage_1.Maps;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jcraft.jsch.*;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NewRead {
    private static final FTPClient ftpClient = new FTPClient();
    private  JSch jsch = new JSch();

    /**
     * 读取 JSON 文件列表，存储至数组中
     *
     * @return
     * @throws IOException
     */
    private JSONArray readJson() {
        File file = new File("E:\\Project_first\\serverInfo.json");
        return JSONUtil.readJSONArray(file, Charset.defaultCharset());
    }

    /**
     * 检测服务器状态是否正常
     */
    private int JsonIsConnect() {
        JSONArray readJson = readJson();
        for (int i = 0; i < readJson.size(); i++) {
            JSONObject entries = JSONUtil.parseObj(readJson.getObj(i));
            String ip = entries.getStr("IP");
            try {
                URL url = new URL(ip);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                Maps maps = new Maps();
                String s = maps.in().get(connection.getResponseCode());
                System.out.println(entries + "\t" + s);
                return responseCode;
            } catch (IOException e) {
                System.out.println("连接超时！");
            }
        }
        return -1;
    }

    /**
     * 创建线程池
     */
    private ThreadPoolExecutor threadPoolDetection() {
        return new ThreadPoolExecutor(
                5,
                5,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10)
        );
    }

    /**
     * 初始化ftp服务器
     */
    // TODO 将可以发送的存在集合内，发送，不能发送的继续尝试连接
    private void SendFileToServer() {
        JSONArray readJson = readJson();
        ThreadPoolExecutor pool = threadPoolDetection();
        for (int i = 0; i < readJson.size(); i++) {
            int finalI = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // FTP服务器主机名
                        JSONObject entries = JSONUtil.parseObj(readJson.getObj(finalI));
                        Session session = jsch.getSession(entries.getStr("UserName"), entries.getStr("IPs"), 22);
                        session.setConfig("StrictHostKeyChecking", "no"); // 跳过主机密钥检查
                        session.setPassword(entries.getStr("PassWord"));
                        session.connect();

                        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
                        channelSftp.connect();
                        //获取服务器文件的时间戳
                        SftpATTRS attrs = channelSftp.lstat("/www/wwwroot/tjv");
                        long mTime = attrs.getMTime();
                        //获取本地文件上传的时间戳
                        File file = new File(entries.getStr("File"));
                        long l = file.lastModified();

                        System.out.println(mTime*1000 +"==>"+ l);
                        if(mTime*1000 < l){
                            //上传文件
                            channelSftp.put(entries.getStr("File"), "/www/wwwroot/tjv");
                        }
                        channelSftp.disconnect();
                        session.disconnect();

                        System.out.println("文件发送成功！");

                    } catch (JSchException | SftpException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }


    public static void main(String[] args) throws IOException {
        NewRead newRead = new NewRead();
        newRead.SendFileToServer();
        //ftp 上传文件
//        try {
//            String server = "8.130.142.87"; // FTP服务器主机名
//            int port = 21; // FTP服务器端厂
//            String username = "test"; // FTP受灵用户名
//            String password = "12345678"; // FTP登灵密码
//            ftpClient.connect(server,port);
//            ftpClient.login(username,password);
//            //启用被动模式
//            ftpClient.enterLocalPassiveMode();
//            System.out.println("Connected to FTP server successfully.");
//            // 进入到要上传文件的目录
//            ftpClient.changeWorkingDirectory("/www/wwwroot/test");
//            // 获取要上传的文件
//            File file = new File("G:\\xiazaiwengjian\\bizhi.png");
//            // 创建输入流
//            try (InputStream inputStream = new FileInputStream(file)) {
//                // 设置上传文件的类型为二进制类型
//                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//                // 上传文件
////                System.out.println("111");
//                boolean a = ftpClient.storeFile(file.getName(), inputStream);
//                if (a) {
//                    System.out.println(a);
//                } else {
//                    int replyCode = ftpClient.getReplyCode();
//                    System.out.println(replyCode);
//                    String replyString = ftpClient.getReplyString();
//                    System.out.println(replyString);
//                }
//            }
//        }catch (Exception s){
//            System.out.println(s);
//
//        }
    }
}

